#include "cust_sign.h"

#include <errno.h>
#include <ez_log.h>
#include <signal.h>
#include <string.h>

static struct ez_signal cust_signals[] = {
    { SIGHUP, 0, "SIGHUP", NULL },
    { SIGINT, 0, "SIGINT", signal_quit_handler },
    { SIGPIPE, 0, "SIGPIPE", NULL },
    { SIGQUIT, 0, "SIGQUIT", signal_quit_handler },
    { SIGTERM, 0, "SIGTERM", signal_quit_handler },
    { 0, 0, "NULL", NULL }
};

static void dispatch_signal_handler(int signo)
{
    struct ez_signal* sig;
    for (sig = cust_signals; sig->signo != 0; sig++) {
        if (sig->signo == signo && sig->handler != NULL) {
            goto find_ez_sig;
        }
    }
    return;

find_ez_sig:
    log_info("signal %d (%s) received", signo, sig->signame);
    sig->handler(sig);
}

void cust_signal_init(void)
{
    int status;
    struct ez_signal* sig;
    struct sigaction sa;

    for (sig = cust_signals; sig->signo != 0; sig++) {
        memset(&sa, 0, sizeof(sa));

        if (sig->handler != NULL) {
            sa.sa_handler = dispatch_signal_handler;
        } else {
            sa.sa_handler = SIG_IGN;
        }
        sa.sa_flags = sig->flags;
        sigemptyset(&sa.sa_mask);

        status = sigaction(sig->signo, &sa, NULL);
        if (status < 0) {
            log_error("sigaction(%s) failed: %s", sig->signame, strerror(errno));
            return;
        }
    }
}
